<template>
  <div class="tbc-app-page-design"
       style="width:395px;height:845px;position: relative;background: url('http://v3.laiketui.com/diy/dist/img/android.d37fdfd5.png') no-repeat;background-size: 100% 100%;transform: scale(0.61) translateY(-260px) translateX(-80px);">
    <!--    transform: scale(0.61) translateY(-240px) translateX(-80px);-->
    <div
        style="box-shadow:0 0 40px 0 rgba(137,157,179,.94);width:98%;height:100%;position:absolute;border-radius:48px;left:1%;z-index:-1;">
    </div>
    <div style="height: 40px"></div>
    <div style="padding-left:10px;padding-right:10px;">
      <div class="hide-scrollbar tbc-transparent"
           style="height: 768px;touch-action:none;box-sizing:border-box;overflow:hidden auto;width: 100%;position:relative;">
        <!--        <div style="position:absolute;top: 0;height: 100px;background: #00a0e9;width: 100%;"></div>-->
        <!--        <background ref="background"></background>-->
        <draggable v-model="list" v-bind="dragOptions" tag="div" :component-data="{
          tag: 'div',
        }" item-key="id" @end="onDragEnd">
          <template #item="{element, index}">
            <div :class="{'tbc-draggable': 1, 'on': element.id === layoutId}"
                 style="position:relative" @click="onModuleItemClick(element.id)">
              <image-group v-if="element.type === 'image-group'"
                           :ref="'component' + element.id"/>
              <carousel v-if="element.type === 'carousel'"
                        :ref="'component' + element.id"/>
              <blank v-if="element.type === 'blank'"
                     :ref="'component' + element.id"/>
              <div class="tbc-layout-delete">
                <span @click.stop="onDeleteClick(index)">删除</span>
              </div>
            </div>
          </template>
        </draggable>

        <!--        <draggable :list="data.list" :options="{draggable:'.tbc-draggable', animation: 300}">-->
        <!--          <div :class="{'tbc-draggable': 1, 'on': index === data.index}"-->
        <!--               v-for="(item, index) in data.list"-->
        <!--               :key="item.id"-->
        <!--               style="position:relative" @click="onModuleItemClick(index)">-->
        <!--            <image-group v-if="item.type === 'image-group'"-->
        <!--                         :ref="'component' + index"/>-->
        <!--            &lt;!&ndash;            <Menu v-if="item.type === 'menu'"&ndash;&gt;-->
        <!--            &lt;!&ndash;                  :ref="'component' + index"/>&ndash;&gt;-->
        <!--            <carousel v-if="item.type === 'carousel'"-->
        <!--                      :ref="'component' + index"/>-->
        <!--            <blank v-if="item.type === 'blank'"-->
        <!--                   :ref="'component' + index"/>-->
        <!--            &lt;!&ndash;            <search v-if="item.type === 'search'"&ndash;&gt;-->
        <!--            &lt;!&ndash;                   :ref="'component' + index"/>&ndash;&gt;-->
        <!--            &lt;!&ndash;            <keyword v-if="item.type === 'keyword'"&ndash;&gt;-->
        <!--            &lt;!&ndash;                    :ref="'component' + index"/>&ndash;&gt;-->

        <!--            <div class="tbc-layout-delete">-->
        <!--              <span @click.stop="onDeleteClick(index)">删除</span>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </draggable>-->
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import {
  defineComponent, defineAsyncComponent,
  getCurrentInstance, reactive, watch, toRefs, PropType
} from 'vue'
import Draggable from 'vuedraggable'

export default defineComponent({
  props: {
    modelValue: {
      type: Array as PropType<any[]>,
      default() {
        return []
      }
    },

    layoutId: {
      type: String,
      default: ''
    },

    data: {
      type: Object,
      default() {
        return {
          list: []
        }
      }
    },
    layout: {
      type: Array,
      default() {
        return []
      }
    }
  },
  components: {
    Draggable,
    blank: defineAsyncComponent(() =>
        import('./views/Blank.vue')),
    ImageGroup: defineAsyncComponent(() =>
        import('./views/ImageGroup.vue')),
    Carousel: defineAsyncComponent(() =>
        import('./views/Carousel.vue')),
  },

  setup(props: any, {emit}) {

    const instance = getCurrentInstance()
    const dragOptions = reactive({
      animation: 300,
      disabled: false
    })
    const state = reactive({
      list: []
    })

    const buildImagesData = () => {
      console.log(('========='))
      const list: { id: number, value: string }[] = []
      props.modelValue.forEach((item) => {
        list.push(item)
      });
      (state.list as { id: number, value: string }[]) = list
      console.log(list)
    }
    const init = (data, index) => {
      console.log('init', instance.refs, index)

      initComponent('component' + index, data, 300)
    }

    // 初始化组件
    const initComponent = (name: string, data: any, maxWait?: number) => {
      try {
        const refs = instance.refs
        console.log(refs[name])
        if (refs[name]) return (refs[name] as any).init(data)
        if (maxWait > 300) return
        setTimeout(() => {
          if (typeof maxWait === 'undefined') maxWait = 30
          initComponent(name, data, maxWait + 30)
        }, 30)
      } catch (e) {
        console.log(e)
      }
    }


    const onModuleItemClick = (id: string) => {
      emit('selected', id)
    }

    const onDragEnd = (): void => {
      const list: any[] = []
      state.list.forEach((item) => list.push(item))
      console.log(list)
      emit('update:modelValue', list)
    }

    watch(() => props.modelValue, function (newVal, oldVal) {
      if (newVal.length === oldVal.length) return
      buildImagesData()
    })

    return {
      ...toRefs(state),
      init,
      dragOptions,
      onDragEnd,
      onModuleItemClick
    }
  }
  // components: {
  //   ,
  //   blank: () => import('./views/Blank'),
  //   imageGroup: () => import('./views/ImageGroup'),
  //   Menu: () => import('./views/Menu'),
  //   carousel: () => import('./views/Carousel'),
  //   Search: () => import('./views/Search'),
  //   background: () => import('./views/Background'),
  //   keyword: () => import('./views/Keyword')
  // },

  // methods: {


  //
  //   onModuleItemClick(index) {
  //     this.$emit('click', index)
  //   },
  //
  //   onDeleteClick(index) {
  //     // return this.$ui.warning('是否确定删除该组件？').then(async () => {
  //       this.$emit('delete', index)
  //     // });
  //   }
  // }
})
</script>
<style scoped>
.tbc-app-page-design * {
  line-height: normal
}

.tbc-layout-delete {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 2px dashed #00a0e9;
  cursor: move;
  display: none;
  z-index: 9;
}

.tbc-layout-delete span {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 50px;
  height: 20px;
  line-height: 20px;
  display: inline-block;
  text-align: center;
  font-size: 16px;
  color: #fff;
  background: rgba(0, 0, 0, .4);
  margin-left: 2px;
  cursor: pointer;
  z-index: 11;
}

.on .tbc-layout-delete, .tbc-draggable:hover .tbc-layout-delete {
  display: block
}
</style>